<?php
class SelectControl extends BaseControl
{
    protected $id;
    protected $list = array();
    protected $selectedValue;
    protected $css = array();

    public function SelectControl(
        $name,
        $data,
        $selectedValue = null,
        $nullItem = null
    )
    {
    	parent::__construct($name);
    	$this->selectedValue = $selectedValue;
        $this->LoadList($data, $nullItem);
    }

    protected function LoadList($data, $nullItem)
    {
        if ($nullItem !== null) $this->list[] = array('id'=>'', 'name'=> $nullItem);
        foreach ($data as $id => $name)
        {
            if (is_array($name))
            {
                $this->list = array_merge($this->list, $data);
                return;
            }
            $this->list[$id] = compact('id', 'name');
        }
    }

    public function Render()
    {
        $this->Replace('css', implode(' ', $this->css));
        $this->Replace('select_id', $this->id ? $this->id : String::ToUrlFriendly($this->name));
        $this->Repeat('options', $this->list, array($this, 'Format'));
        return parent::Render();
    }

    public function Format($item)
    {
        $item['selected'] =  $item['id'] == $this->selectedValue ? 'selected="selected"' : null;
        return $item;
    }

    public function AddCssClass($class)
    {
        $this->css[$class] = $class;
    }

    public function SetId($id)
    {
        $this->id = $id;
    }

    public static function GetOptions($list, $selected_id = null, $empty_option = true)
    {
        if ($empty_option) $options[] = "<option value=''></option>";
        else if (is_null($empty_option)) $options[] = '<option value="#NULL"></option>';
        foreach($list as $id=>$name)
        {
            $selected = null;
            if ($selected_id !== null && $id==$selected_id)
                $selected = ' selected="selected"';
            $options[] = "<option value=\"$id\"$selected>$name</option>";
        }
        return implode(null, $options);
    }

    public function SetStyle($style)
    {
        $this->Replace('style', $style);
    }

    public function AddOption($label, $value = null)
    {
        $this->list[$value] = array(
            'id' => $value,
            'name' => $label
        );
    }

    public function SetSelectedLabel($key, $label)
    {
        $this->list[$key] = array(
            'id' => $key,
            'name' => $label
        );
    }
}
?>